import {
  EventBase,
  UIActionUtil,
  IColumnState,
  SysUIActionTag,
  IViewController,
  PanelItemController,
  ISearchFormController,
} from '@ibiz-template/runtime';
import { IPanelRawItem } from '@ibiz/model-core';
import { GridController } from '../../controller';

/**
 * 预置表格工具栏控制器
 *
 * @export
 * @class GridToolbarController
 * @extends {PanelItemController<IPanelRawItem>}
 */
export class GridToolbarController extends PanelItemController<IPanelRawItem> {
  /**
   * 视图控制器
   *
   * @readonly
   * @type {IViewController}
   * @memberof GridToolbarController
   */
  get view(): IViewController {
    return this.panel.view;
  }

  /**
   * 表格控制器
   *
   * @readonly
   * @type {(GridController | undefined)}
   * @memberof GridToolbarController
   */
  get grid(): GridController | undefined {
    return this.panel.view.getController('grid') as GridController;
  }

  /**
   * 显示重置按钮
   *
   * @readonly
   * @type {boolean}
   * @memberof GridToolbarController
   */
  get showReset(): boolean {
    return !!(this.grid && this.grid.state.columnModelCach)
  }

  /**
   * 搜索表单控制器
   *
   * @readonly
   * @type {(ISearchFormController | undefined)}
   * @memberof GridToolbarController
   */
  get searchForm(): ISearchFormController | undefined {
    return this.panel.view.getController('searchform') as ISearchFormController;
  }

  /**
   * 获取事件参数
   *
   * @return {*}
   * @memberof GridToolbarController
   */
  getEventArgs(): Omit<EventBase, 'eventName'> {
    return {
      data: [],
      view: this.view,
      ctrl: this.panel,
      context: this.panel.context,
      params: this.panel.params,
      targetName: this.model.name!,
    };
  }

  /**
   * 刷新
   *
   * @protected
   * @memberof GridToolbarController
   */
  refresh(): void {
    this.view.callUIAction(SysUIActionTag.REFRESH);
  }

  /**
   * @description 重置表格列
   * @protected
   * @memberof GridToolbarController
   */
  resetColumn(): void {
    this.grid?.resetColumnStates();
  }

  /**
   * 导出
   *
   * @protected
   * @memberof GridToolbarController
   */
  async export(
    event: MouseEvent,
    type: 'maxRowCount' | 'activatedPage',
  ): Promise<void> {
    this.view.callUIAction(SysUIActionTag.EXPORT_EXCEL, { event, params: { type, startPage: 1, endPage: 9999 } });
  }

  /**
   * 保存列状态
   *
   * @memberof GridToolbarController
   */
  saveColumnStates(): void {
    this.grid?.calcColumnFixed();
    this.grid?.saveColumnStates();
  }

  /**
   * 设置列显示状态
   *
   * @param {IColumnState} columnState
   * @memberof GridToolbarController
   */
  setColumnVisible(columnState: IColumnState): void {
    if ([2, 3].includes(columnState.hideMode)) return;
    columnState.hidden = !columnState.hidden;
    this.saveColumnStates();
  }

  /**
   * 切换搜索表单的显示与否
   *
   * @protected
   * @memberof GridToolbarController
   */
  toggleFilter(): void {
    this.view.callUIAction(SysUIActionTag.TOGGLE_FILTER);
  }
}
